package com.sdksoft.readcard

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Handler
import android.os.Looper
import android.util.Log
import cn.mtjsoft.ocr_android.ScanningManager
import cn.mtjsoft.ocr_android.config.Config
import cn.mtjsoft.ocr_android.enums.ScanTypeEnum
import cn.mtjsoft.ocr_android.interfaces.ScanResultListener
import com.csht.bean.EPassportData
import com.csht.bean.IdCardData
import com.csht.enums.ReadCardType
import com.csht.enums.StatusCode
import com.csht.listener.InitListener
import com.csht.listener.ReadCardListener
import com.sdksoft.readcard.databinding.ActivityUsbHuzhaoBinding
import com.sdksoft.readcard.databinding.PortSettingBinding
import com.csht.utils.HHTipUtils
import org.json.JSONObject
import java.util.*

class PassportHuZhaoActivity : BaseInitActivity(), ReadCardListener {

    private val TAG = "readcard"

    private lateinit var portSettingBinding: PortSettingBinding
    private lateinit var usbHuZhaoBinding: ActivityUsbHuzhaoBinding

    private var isInitOk = false

    private var readType = 0

    override fun initView() {
        super.initView()
        setTitleText("护照读卡")
        readType = intent.getIntExtra("type", 0)
        portSettingBinding = PortSettingBinding.inflate(layoutInflater)
        usbHuZhaoBinding = ActivityUsbHuzhaoBinding.inflate(layoutInflater)
        baseActivityBinding.llContent.apply{
            addView(usbHuZhaoBinding.root, 0)
            if (readType == 0) {
                addView(portSettingBinding.root, 0)
            }
        }
        usbHuZhaoBinding.apply {
            btnOcr.setOnClickListener {
                ocr()
            }
            btnStartRead.setOnClickListener {
                startRead()
            }
        }
        portSettingBinding.apply {
            save.setOnClickListener {
                if (isInitOk) {
                    readCardManager.readCardStop()
                    isInitOk = false
                }
                initSDK()
            }
        }
        initSDK()
    }

    private fun test() {
        // 循环测试，正式的去掉
        if (BuildConfig.DEBUG) {
            mainHandler.removeCallbacksAndMessages(null)
            mainHandler.postDelayed({
                startRead()
            }, 2000)
        }
    }

    /**
     * 初始化SDK
     */
    private fun initSDK() {
        if (readType == 0) {
            portSettingBinding.apply {
                readSettingBuilder
                    .buildReadCardType(ReadCardType.SERIALPORT_DK_PASSPORT)
                    // 设置串口号、波特率（串口读卡时需要设置）
                    .buildSerialPort(
                        deviceFilePath.text.toString().trim(),
                        baudrate.text.toString().trim().toInt()
                    )
            }
        } else if (readType == 1) {
            readSettingBuilder.buildReadCardType(ReadCardType.USB_DK_PASSPORT)
        } else {
            readSettingBuilder.buildReadCardType(ReadCardType.USB_PASSPORT)
        }
        readCardManager.readCardInit(object :InitListener {
            override fun onResponse(code: Int, msg: String) {
                when (code) {
                    StatusCode.ININ_ING.code -> {
                        Log.d(TAG, "初始化中. $msg")
                    }
                    StatusCode.ININ_OK.code -> {
                        isInitOk = true
                        runOnUiThread {
                            HHTipUtils.getInstance().showToast(this@PassportHuZhaoActivity, "初始化成功")
                        }
                    }
                    else -> {
                        isInitOk = false
                        runOnUiThread {
                            HHTipUtils.getInstance().showToast(this@PassportHuZhaoActivity, "初始化失败")
                        }
                    }
                }
            }
        })
    }

    /**
     * OCR识别
     */
    private fun ocr() {
        usbHuZhaoBinding.apply {
            ScanningManager.instance.openScanningActivity(
                this@PassportHuZhaoActivity,
                Config(true, ScanTypeEnum.PASSPORT_MRZ, 1, 0, true, object : ScanResultListener {
                    override fun onSuccessListener(value: String?, bitmap: Bitmap?) {
                        value?.let {
                            try {
                                ivHead.setImageResource(0)
                                val jsonObject = JSONObject(it)
                                tvMsg.apply {
                                    text = "OCR识别成功--"
                                    append(System.currentTimeMillis().toString())
                                    append("\n")
                                    append("护照机读码：")
                                    append("\n")
                                    append(jsonObject.optString("MRZLine1", ""))
                                    append("\n")
                                    append(jsonObject.optString("MRZLine2", ""))
                                    append("\n")
                                }
                                documentNumber.setText(
                                    jsonObject.optString(
                                        "documentNumber", ""
                                    )
                                )
                                dateOfBirth.setText(jsonObject.optString("dateOfBirth", ""))
                                dateOfExpiry.setText(jsonObject.optString("dateOfExpiry", ""))
                                bitmap?.let {
                                    ivHead.setImageBitmap(bitmap)
                                }
                            } catch (e: Exception) {
                                tvMsg.text = e.message
                            }
                        }
                    }

                    override fun onFailureListener(error: String) {
                        tvMsg.text = error
                    }
                })
            )
        }
    }

    private fun startRead() {
        if (isInitOk.not()) {
            HHTipUtils.getInstance().showToast(this@PassportHuZhaoActivity, "没有初始化成功")
            return
        }
        usbHuZhaoBinding.apply {
            val documentNumberStr = documentNumber.text.toString().trim().toUpperCase(Locale.ROOT)
            val dateOfBirthStr = dateOfBirth.text.toString().trim()
            val dateOfExpiryStr = dateOfExpiry.text.toString().trim()
            if (documentNumberStr.isEmpty() || dateOfBirthStr.isEmpty() || dateOfExpiryStr.isEmpty()) {
                HHTipUtils.getInstance().showToast(this@PassportHuZhaoActivity, "请完整填写参数")
                return@apply
            }
            HHTipUtils.getInstance()
                .showProgressDialog(this@PassportHuZhaoActivity, "读取中，请勿移动", false)
            // 开始读取护照
            readCardManager.readPassportStart(
                Intent(), documentNumberStr, dateOfBirthStr, dateOfExpiryStr, this@PassportHuZhaoActivity
            )
        }
    }

    override fun onReadCardState(type: Int, msg: String?) {
        if (type == StatusCode.READCARD_FAILE.code) {
            HHTipUtils.getInstance().dismissProgressDialog()
            HHTipUtils.getInstance().showToast(this, "type:$type\n$msg")
            usbHuZhaoBinding.tvMsg.text = "\n----------------------------\nstatus: $type  ，msg:$msg"
            test()
        } else if (type == StatusCode.READCARD_SUCCESS.code) {
            HHTipUtils.getInstance().dismissProgressDialog()
            HHTipUtils.getInstance().showToast(this, "type:$type\n$msg")
            test()
        } else if (type == StatusCode.FIND_CARD_SUCCESS.code) {
            if (!HHTipUtils.getInstance().progressDialogIsShowing()) {
                HHTipUtils.getInstance().showProgressDialog(this, "正在读取,请勿移动", false)
            }
        }
    }

    override fun onReadICCardSuccess(icNumber: String?, type: Int) {
    }

    override fun onReadIDCardSuccess(bean: IdCardData?) {
    }

    override fun onReadPassportSuccess(bean: EPassportData?) {
        super.onReadPassportSuccess(bean)
//        usbHuZhaoBinding.apply {
//            documentNumber.setText("")
//            dateOfBirth.setText("")
//            dateOfExpiry.setText("")
//        }
        HHTipUtils.getInstance().dismissProgressDialog()
        bean?.apply {
            usbHuZhaoBinding.tvMsg.apply {
                text = "姓名："
                append(nameOfHolder)
                append(" / $primaryIdentifier $secondaryIdentifier")
                append("\n性别：")
                append(if (gender.startsWith("M")) "男" else "女")
                append(" / $gender")
                append("\n生日：")
                append(dateOfBirth)
                append("\n国家码：")
                append(nationality)
                append("\n有效期：")
                append(dateOfExpiry)
                append("\n护照号码：")
                append(documentNumber)
                append("\n个人号码：")
                append(personNumber)
                append("\n护照机读码：")
                append(mrz)

//                if (passiveAuth) {
//                    append("\n\npassiveAuthStr: pass")
//                } else {
//                    append("\n\npassiveAuthStr: failed")
//                }
//                if (chipAuth) {
//                    append("\nchipAuthStr: pass")
//                } else {
//                    append("\nchipAuthStr: failed")
//                }
                append("\n\n耗时：$duration ms")
            }
            if (image == null) {
                usbHuZhaoBinding.ivHead.setImageResource(0)
            } else {
                image?.let {
                    val bitmap = BitmapFactory.decodeByteArray(it, 0, it.size)
                    usbHuZhaoBinding.ivHead.setImageBitmap(bitmap)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        HHTipUtils.getInstance().dismissProgressDialog()
        mainHandler.removeCallbacksAndMessages(null)
        readCardManager.readCardStop()
    }
}